﻿using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Windows.Forms;
using EncriptionLibrary;
using System.Diagnostics;

namespace GOA_Client
{
    class Client
    {
        private TcpClient client;
        private ClientGUI gui;
        public int patientnummer { get; set; }
        //static void Main(string[] args)
        public Client(ClientGUI gui, int useridnummer)
        {
            patientnummer = useridnummer;
            this.gui = gui;
            Boolean connection = false;
            while(!connection)
            {
                try
                {
                    //delano: 5.63.80.33
                    client = new TcpClient("127.0.0.1", 1333);
                    connection = true;
                }
                catch (SocketException)
                {
                    MessageBox.Show("ERROR \r\n" +
                                    "Kan geen verbinding maken met de server \r\n"+
                                    "Misschien is er al een connectie geopend \r\n"+
                                    "Klik OK om nog een keer te proberen");
                    Application.Exit();
                }
            }
            //bool done = false;
            Debug.WriteLine("Type 'terminate' to end connection");
            SendMessage("" + patientnummer);
            //Thread clientThread = new Thread(new ThreadStart(runClient));
            //clientThread.Start();
            //runClient();

            //while (!done)
            //{
            //    Console.Write("Enter a message to send to server:");
            //    string message = Console.ReadLine();
            //    ndMessage(message);
            //    string response = ReadResponse(client);
            //    Debug.WriteLine("response: " + response);
            //    done = response.Equals("BYE");
            //}

        }

        public static string encryption(String Message, String Key, enEnCryptDecrypt EnC)
        {
            int messageCount, keyCount, value = 0;

            StringBuilder strRetVal = new StringBuilder();
            if (Message.Length > 0 && Key.Length > 0)
            {
                try
                {
                    for (messageCount = 0, keyCount = 0; messageCount < Message.Length; messageCount++, keyCount++)
                    {
                        if (keyCount >= Key.Length) keyCount = 0; // Rotates the Key string counter to Zero when character value is traversed till end

                        if (EnC == enEnCryptDecrypt.ENCRYPT)
                            value = (Message[messageCount]) + (Key[keyCount]); //When Encryption is required we add ascii value of key with Message
                        else
                            value = (Message[messageCount]) - (Key[keyCount]); // When Decryption is required we subtract ascii value of key with Message

                        strRetVal.Append((char)(value)); // Here we convert the ascii value to character and Append that to Stringbuilder
                    }
                }
                catch (Exception ex)
                {
                    // Clears the StringBuilder and Append Error Message in it.
                    strRetVal.Remove(0, strRetVal.Length);
                    strRetVal.Append("Error in Ecrypting:-" + ex.Message);
                }
            }
            else
            {
                // Append Return message with proper valid string required.
                strRetVal.Append("Enter valid Message and Key");
            }

            return strRetVal.ToString(); //Returns the Processed String.
        }

        public void SendMessage(string message)
        {
            try
            {
                string encrMessage = encryption(message, "5h589h5h", enEnCryptDecrypt.ENCRYPT);
                byte[] bytes = Encoding.Unicode.GetBytes(encryption(message, "5h589h5h", enEnCryptDecrypt.ENCRYPT)); 
                client.GetStream().Write(bytes, 0, bytes.Length);
            }
            catch (IOException)
            {
            }
            catch (InvalidOperationException)
            {

            }
        }

        public string ReadMessage()
        {
                byte[] buffer = new byte[256];
                int totalRead = 0;
                try
                {
                    do
                    {
                        try
                        {
                            int read = client.GetStream().Read(buffer, totalRead, buffer.Length - totalRead);
                            totalRead += read;
                        }
                        catch (IOException) { }
                        catch (InvalidOperationException) { }
                    }

                    while (client.GetStream().DataAvailable);
                }
                catch (InvalidOperationException)
                {
                    gui.timer.Stop();
                    MessageBox.Show("De server is afgesloten");
                    Environment.Exit(0);
                }
                return encryption(Encoding.Unicode.GetString(buffer, 0, totalRead), "5h589h5h", enEnCryptDecrypt.DECRYPT);
        }

        public void stopClient() {
            client.Close();
        }

        public void restartClient() {
            client.Connect("127.0.0.1",1333);
        }
    }
}
